// pages/audiotion6/audiotion6.js
const app = getApp()
var id=''
let name = ''
let contact = ''
let place = ''
let remark = ''

Page({
  data: {
    good:{},
    open_id:[],
    show: false,
    duration: 300,
    position: 'right',
    round: true,
    overlay: true,
    customStyle: '',
    overlayStyle: '',
    userInfo: {},
    hasUserInfo: false,
  },

  onLoad(options) {
    console.log("audio传值",options)
    id = options.id
    this.getDetail()
    this.getOpenid()

    var user = wx.getStorageSync('user');
    if(user) {
      console.log('用户信息已授权')
      this.setData({
        hasUserInfo:true,
        userInfo: user,
      })
    }
  },

  onShareAppMessage() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  onShareTimeline(e) {
    console.log(e)
    return {
      title: '分享至朋友圈',
      path:''
    }
  },

  getDetail() {
    wx.cloud.database().collection('try_5-10')
    .doc(id)
    .get()
    .then(res => {
      console.log('物品详情查询成功',res)
      this.setData({
        good:res.data
      })
    })
    .catch(res => {
      console.error('物品详情查询失败',res)
    })
  },

  //拉起弹窗
 send_pop() {
   console.log("拉起弹窗")
    const position = "bottom"
    let customStyle = ''
    let duration = this.data.duration
    switch(position) {
      case 'top':
      case 'bottom': 
        customStyle = 'height: 80%;'
        break
      case 'right':
        break
    }
    this.setData({
      position,
      show: true,
      customStyle,
      duration
    })
  },

  get_Profile() {
    wx.getUserProfile({
      lang:'zh_CN',
      desc: '用于完善会员资料', 
      success: (res) => {
        console.log("用户信息",res)
        if (!this.hasUserInfo && res.userInfo) {
          wx.showToast({
            title: '授权成功',
          })
          wx.setStorageSync('user',res.userInfo)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.send_pop()
        }
      }
    })
  },

  //获取openid
  getOpenid() {
    wx.cloud.callFunction({
      name:"getopenid"
    }).then(res=>{
      console.log("获取openid成功",res)
      this.setData({
        open_id:res
      })
    }).catch(err=>{
      console.log("获取失败",err)
    })
  },

  exit() {
    this.setData({show: false})
    this.sendOne()
    this.addGM_list()
  },

  //获取用户授权
  //用于拾物人向失主发送物品信息
  authorization(e) {
    let that = this
    console.log("abaaba",this.data.open_id.result.openid)
    console.log(e)
    if (wx.requestSubscribeMessage) {
      wx.requestSubscribeMessage({
        tmplIds: ['QPLrrmYm_Kt8giQiZHLJhPW-wQXxy5a4CrwgNSpMZe4'],
        success(res) {
          if (res['QPLrrmYm_Kt8giQiZHLJhPW-wQXxy5a4CrwgNSpMZe4'] === 'accept') {
            console.log("授权成功",res)
            that.send_pop(e)
          } else if (res['QPLrrmYm_Kt8giQiZHLJhPW-wQXxy5a4CrwgNSpMZe4'] ==='reject') {
            console.log("取消授权")
          } else {
            wx.showToast({
              title: '授权订阅消息有误',
              icon: 'none'
            })
          }
        },
        fail(res) {
          if (res.errCode == 20004) {
          	// 显示引导设置弹窗
            that.setData({
              isShowSetModel: true
            })
          }else{
          	// 其他错误信息码，对应文档找出原因
            wx.showModal({
              title: '提示',
              content: res.errMsg,
              showCancel: false
            })
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请更新您微信版本，来获取订阅消息功能',
        showCancel: false
      })
    }
    // wx.requestSubscribeMessage({
    //   tmplIds: ['QPLrrmYm_Kt8giQiZHLJhPW-wQXxy5a4CrwgNSpMZe4'],
    //   success:(res)=> {
    //     console.log("授权成功",res)
    //     console.log("发布人openid",this.data.good._openid)
    //     this.send_pop(e)
    //   },
    //   fail(err) {
    //     console.log("授权失败",err)
    //   },
    // })
  },

  addGM_list() {
    console.log(this.data.good.name)
    console.log("用户信息",this.data.userInfo)
    wx.cloud.database().collection('GoodMan_list')
    .add({
      data:{
        lthing:this.data.good.name,
        nickName:this.data.userInfo.nickName,
        avatarUrl:this.data.userInfo.avatarUrl
      },
      success(res) {
        console.log("上传成功",res)
      },
      fail(err) {
        console.log("上传失败",err)
      }
    })
  },

  //发送消息给单个用户
  sendOne() {
    if (
      name==null || name=='' || contact==null || contact=='' || place==null || place=='' || remark==null || remark==''
    ){
      wx.showToast({
        icon:'none',
        title: '还有选项没有输入',
      })
      return
    }
    wx.cloud.callFunction({
      name: "fasong",
      data: {
        openid:this.data.good._openid,
        name:name,
        contact:contact,
        place:place,
        remark:remark
      }
    }).then(res => {
      console.log("发送成功",res.result.errMsg)
      console.log("测试",this.data.good._openid)
      wx.showToast({
        title: '发送成功',
        duration:2000,
      })
    }).catch(err => {
      console.log("发送失败",err)
    })
  },

  getName(event) {
    console.log(event.detail.value)
    name = event.detail.value
  },
  getPhone(event) {
    console.log(event.detail.value)
    contact = event.detail.value
  },
  getPlace(event) {
    console.log(event.detail.value)
    place = event.detail.value
  },
  getStorage(event) {
    console.log(event.detail.value)
    remark = event.detail.value
  },

  //拾物提醒发布记录（统计用户发布“捡到”提醒的次数)
  caution() {
    wx.cloud.database().collection("GoodMan_list")
    .add({
      data:{
        user:this.data.open_id
      },
      success(res) {
        console.log("上传成功",res)
      },
      fail(err) {
        console.log("上传失败",err)
      }
    })
  },

  //点击预览图片
  f1:function(event){
    console.log(this.data.good.pic1)
    let currentUrl = this.data.good.pic1
    var dataArray = [];
    dataArray[0] = currentUrl
    wx.previewImage({
      urls: dataArray, // 需要预览的图片http链接列表
      current:dataArray[0],
      success:function(res){
        console.log("1111",res)
      },
      fail(err) {
        console.log(err)
      }
    })
  },
})